package dang.action.user;

import java.io.Serializable;

import dang.action.DangAction;
import dang.common.DigestUtil;
import dang.common.EmailUtil;
import dang.common.VerifyUtil;
import dang.dao.DaoFactory;
import dang.dao.UserDao;
import dang.entity.User;

public class RegisterAction extends DangAction implements Serializable {
	private User user;
	private String validateCode;

	/**
	 * 
	 */
	public String execute() throws Exception {
		String code = (String) session.get("validateCode");
		if (!code.equalsIgnoreCase(validateCode)) {
			return "registerError";
		}

		UserDao userDao = DaoFactory.getUserDao();

		if ("".equals(user.getEmail())
				|| userDao.findByEmail(user.getEmail())!=null)
			return "registerError";
		// 1.将用户信息写入d_user表
		// 将密码加密
		String pass = DigestUtil.md5(user.getPassword());
		user.setPassword(pass);
		userDao.save(user);
		// 2.生成邮箱激活码
		code = VerifyUtil.generateCode(user.getId());
		// 3.给用户发送邮件
		EmailUtil.send(user.getEmail(), code);
		// 4.将激活码uuid部分更新到d_user表
		String uuid = VerifyUtil.getUUID(code);
		user.setEmail_verify_code(uuid + "-" + user.getId());
		user.setIs_email_verify("no");
		userDao.update(user);
		// 注册后验证码无效
		session.put("validateCode", "你是猪");
		return "next";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

}
